import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  NavBar, 
  Button, 
  Input, 
  Form, 
  Toast,
  Dialog,
  ImageUploader,
  Radio
} from 'antd-mobile';
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';

import axios from '../../axios';
import './Com/Editinfo.css';

interface UserInfo {
  id: string;
  username: string;
  nickname: string;
  avatar: string;
  phone: string;
  email: string;
  gender: string;
  city: string;
  vipLevel: number;
  points: number;
}



const Editinfo: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [fileList, setFileList] = useState<ImageUploadItem[]>([]);

  // 性别选择选项
  const genderOptions = [
    { label: '男', value: '男' },
    { label: '女', value: '女' },
    { label: '保密', value: '保密' }
  ];

  // 获取用户ID
  const getUserId = () => {
    return localStorage.getItem('yonghuId') || 'yonghu_001';
  };

  // 获取用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const userId = getUserId();
        const response = await axios.get(`http://localhost:3000/hy/yonghu/${userId}`);
        
        if (response.data.code === 200 && response.data.data) {
          const userData = response.data.data;
          setUserInfo(userData);
          
          // 设置表单默认值
          form.setFieldsValue({
            nickname: userData.nickname,
            phone: userData.phone,
            email: userData.email,
            gender: userData.gender || '保密'
          });

          // 设置头像
          if (userData.avatar) {
            setFileList([{
              url: userData.avatar.startsWith('http') ? userData.avatar : `http://localhost:3000${userData.avatar}`
            }]);
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        Toast.show('获取用户信息失败');
      }
    };

    fetchUserInfo();
  }, [form]);

  const handleBack = () => {
    navigate('/app/my');
  };

  // 头像上传
  const handleAvatarUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('avatar', file);
    
    try {
      const response = await axios.post('http://localhost:3000/hy/yonghu/upload-avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (response.data.code === 200) {
        // console.log('后端返回的avatarUrl',response.data.data.avatarUrl);
        return {
          url: `http://localhost:3000${response.data.data.avatarUrl}`
        };
      } else {
        throw new Error(response.data.message || '上传失败');
      }
    } catch (error) {
      console.error('头像上传失败:', error);
      Toast.show('头像上传失败');
      throw error;
    }
  };

// 保存资料
const handleSave = async () => {
    try {
      // 表单验证
      const values = await form.validateFields();
      
      setLoading(true);
      
      const userId = getUserId();
      const updateData = {
        nickname: values.nickname,
        avatar: fileList.length > 0 ? fileList[0].url : userInfo?.avatar || '',
        gender: values.gender || '保密',
        phone: values.phone,
        email: values.email
      };

      const response = await axios.put(`http://localhost:3000/hy/yonghu/${userId}/profile`, updateData);
      
      if (response.data.code === 200) {
        Toast.show({
          content: '保存成功',
          position: 'center',
          duration: 2000
        });
        
        // 延迟返回，让用户看到成功提示
        setTimeout(() => {
          navigate('/app/my');
        }, 1500);
      } else {
        Toast.show({
          content: response.data.message || '保存失败',
          position: 'center'
        });
      }
    } catch (error: unknown) {
      console.error('保存失败:', error);
      
      if (error && typeof error === 'object' && 'response' in error) {
        const axiosError = error as { response?: { data?: { message?: string } } };
        if (axiosError.response?.data?.message) {
          Toast.show({
            content: axiosError.response.data.message,
            position: 'center'
          });
        } else {
          Toast.show({
            content: '保存失败，请重试',
            position: 'center'
          });
        }
      } else {
        Toast.show({
          content: '保存失败，请重试',
          position: 'center'
        });
      }
    } finally {
      setLoading(false);
    }
  };

  // 确认保存对话框
  const showSaveConfirm = () => {
    Dialog.confirm({
      content: '确定要保存修改的个人信息吗？',
      onConfirm: handleSave
    });
  };

  if (!userInfo) {
    return (
      <div className="editinfo-container">
        <NavBar onBack={handleBack} back="返回">
          编辑资料
        </NavBar>
        <div className="loading-container">
          <div>正在加载用户信息...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="editinfo-container">
      <NavBar onBack={handleBack} back="返回">
        编辑资料
      </NavBar>
      
      <div className="editinfo-content">
        <Form form={form} layout="horizontal">
          {/* 头像上传 */}
          <Form.Item label="头像">
            <div className="avatar-upload">
                <ImageUploader
                  value={fileList}
                  onChange={setFileList}
                  upload={handleAvatarUpload}
                  maxCount={1}
                  accept="image/*"  //限制上传图片格式
                  style={{ '--cell-size': '60px' }}
                  showUpload={fileList.length < 1}
                />
            </div>
          </Form.Item>

          {/* 昵称 */}
          <Form.Item 
            name="nickname" 
            label="昵称"
            rules={[
              { required: true, message: '请输入昵称' },
              { max: 20, message: '昵称不能超过20个字符' }
            ]}
          >
            <Input placeholder="请输入昵称" clearable />
          </Form.Item>

          {/* 手机号 */}
          <Form.Item 
            name="phone" 
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" clearable />
          </Form.Item>

          {/* 邮箱 */}
          <Form.Item 
            name="email" 
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" clearable />
          </Form.Item>

          {/* 性别 */}
          <Form.Item name="gender" label="性别">
            <Radio.Group>
              {genderOptions.map(option => (
                <Radio style={{ '--icon-size': '15px', marginRight: '0.3rem' }} key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          {/* VIP等级（只读） */}
          <Form.Item label="会员等级">
            <Input 
              value={userInfo.vipLevel?`VIP${userInfo.vipLevel}`:'普通用户'} 
              disabled 
              style={{ '--color': '#999' }}
            />
          </Form.Item>

          {/* 积分（只读） */}
          <Form.Item label="积分">
            <Input 
              value={userInfo.points.toString()} 
              disabled 
              style={{ '--color': '#999' }}
            />
          </Form.Item>
        </Form>
        
        <div className="save-section">
          <Button 
            color="primary" 
            size="large" 
            onClick={showSaveConfirm}
            loading={loading}
            block
          >
            {loading ? '保存中...' : '保存资料'}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Editinfo;